// 云函数入口文件 poiManager/index.js
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })

exports.main = async (event) => {
  const db = cloud.database()
  const { pois, action = 'batchUpsert' } = event

  try {
    if (!Array.isArray(pois)) {
      throw new Error('参数类型错误：pois必须为数组')
    }

    const results = {
      total: pois.length,
      success: 0,
      failed: 0,
      errors: []
    }

    const BATCH_SIZE = 50
    for (let i = 0; i < pois.length; i += BATCH_SIZE) {
      const batch = pois.slice(i, i + BATCH_SIZE)
      const batchResults = await processBatch(batch, i)
      results.success += batchResults.success
      results.failed += batchResults.failed
      results.errors.push(...batchResults.errors)
    }

    return {
      code: 200,
      message: '处理完成',
      data: results
    }

  } catch (err) {
    console.error('云函数执行失败:', err)
    return {
      code: err.code || 500,
      message: err.message,
      data: null
    }
  }

  async function processBatch(batch, batchStartIndex) {
    const batchResult = {
      success: 0,
      failed: 0,
      errors: []
    }

    // 步骤1：批次内ID去重
    const idMap = new Map()
    const uniqueBatch = []
    batch.forEach((poi, batchIndex) => {
      const id = poi.id?.toString()
      if (!id) {
        batchResult.failed++
        batchResult.errors.push({
          index: batchStartIndex + batchIndex,
          id: 'undefined',
          error: '缺少ID字段'
        })
        return
      }

      if (idMap.has(id)) {
        batchResult.failed++
        batchResult.errors.push({
          index: batchStartIndex + batchIndex,
          id,
          error: '批次内重复ID'
        })
      } else {
        idMap.set(id, true)
        uniqueBatch.push({ poi, batchIndex })
      }
    })

    // 步骤2：数据库存在性检查
    const idsToCheck = uniqueBatch.map(item => item.poi.id.toString())
    let existingDocs = []
    if (idsToCheck.length > 0) {
      existingDocs = await db.collection('Pois')
        .where({ _id: db.command.in(idsToCheck) })
        .field({ _id: true })
        .get()
    }
    const existingIds = new Set(existingDocs.data.map(doc => doc._id))

    // 步骤3：处理唯一记录
    const tasks = uniqueBatch.map(async ({ poi, batchIndex }) => {
      const id = poi.id.toString()
      const globalIndex = batchStartIndex + batchIndex

      if (existingIds.has(id)) {
        batchResult.failed++
        batchResult.errors.push({
          index: globalIndex,
          id,
          error: '数据库已存在'
        })
        return
      }

      try {
        if (!poi.location) throw new Error('缺少location字段')

        const { id: _, ...cleanData } = poi
        const safeData = {
          ...cleanData,
          location: db.Geo.Point(...poi.location.split(',').map(Number)),
          _createTime: db.serverDate(),
          _updateTime: db.serverDate()
        }

        await db.collection('Pois').doc(id).set({ data: safeData })
        batchResult.success++
      } catch (err) {
        batchResult.failed++
        batchResult.errors.push({
          index: globalIndex,
          id,
          error: err.message
        })
      }
    })

    await Promise.all(tasks)
    return batchResult
  }
}